package com.speedcar.base.util;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.speedcar.base.exception.ErrorCode;
import com.speedcar.base.exception.SpeedCarBusinessException;
import com.speedcar.base.model.GeoResult;
import com.speedcar.base.model.HttpReqInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 地理编码工具类
 */
@Slf4j
public class MapboxGeoUtil {

    public static final String BASE_URL = "https://api.mapbox.com/search/geocode/v6/forward";

    /**
     * 获取经纬度
     *
     * @param county      区域，中国CN,俄罗斯RU
     * @param address     地址，中国支持到市级别
     * @param accessToken accessToken
     * @return GeoResult
     */
    public static GeoResult geocode(String county, String address, String accessToken) {
        List<HttpReqInfo> param = new ArrayList<>();
        param.add(new HttpReqInfo("access_token", accessToken));
        param.add(new HttpReqInfo("q", address));
        if (StringUtils.isNotBlank(county)) {
            param.add(new HttpReqInfo("country", county));
        }
        try {
            String result = HttpClientUtil.sendGet(BASE_URL, param);
            if (StringUtils.isBlank(result)) {
                throw new SpeedCarBusinessException(ErrorCode.COMMON_ERROR, "获取地址信息失败");
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONArray features = jsonObject.getJSONArray("features");
            if (features == null || features.isEmpty()) {
                throw new SpeedCarBusinessException(ErrorCode.COMMON_ERROR, "获取地址信息失败");
            }
            JSONObject feature = features.getJSONObject(0);
            JSONObject geometry = feature.getJSONObject("geometry");
            JSONArray coordinates = geometry.getJSONArray("coordinates");
            GeoResult geoResult = new GeoResult();
            geoResult.setAddress(address);
            geoResult.setLongitude(coordinates.getString(0));
            geoResult.setLatitude(coordinates.getString(1));
            return geoResult;
        } catch (Exception e) {
            log.error("获取地址信息失败", e);
            throw new SpeedCarBusinessException(ErrorCode.COMMON_ERROR, "获取地址信息失败");
        }
    }
}
